import { limitRange } from "../utils";
import { operateType } from "@/enum";

export default function (
    { axisRef, axisBoxRef, boxWrapperRef },
    scaleGroup,
    translateGroup,
    config,
    status
) {
    watch(
        () => boxWrapperRef.value,
        (val) => {
            val.addEventListener("mousedown", (event) => {
                translateGroup.value.offset =
                    translateGroup.value.offset ?? -scaleGroup.value.offset;
                translateGroup.value.startX = -scaleGroup.value.offset;
                translateGroup.value.scale = scaleGroup.value.scale;

                document.addEventListener("mousemove", onMouseMove);
                document.addEventListener("mouseup", onMouseUp);
                document.ondragstart = function (ev) {
                    ev.preventDefault();
                };
                document.ondragend = function (ev) {
                    ev.preventDefault();
                };

                boxWrapperRef.value.classList.add("axis-wrapper--dragged");
                status.value = operateType.MOVE;
            });
        }
    );

    function onMouseMove(event) {
        const { movementX } = event;
        const viewportWidth = axisRef.value.clientWidth;
        const axisWidth = boxWrapperRef.value.clientWidth;
        const min = viewportWidth - axisWidth;
        const max = 0;
        translateGroup.value.offset = limitRange(
            min,
            max,
            translateGroup.value.offset + movementX
        );
        boxWrapperRef.value.style.left = translateGroup.value.offset + "px";

        const left = axisRef.value.offsetLeft;
        const top = axisRef.value.offsetTop;
        const right = axisRef.value.offsetLeft + axisRef.value.offsetWidth;
        const bottom = axisRef.value.offsetTop + axisRef.value.offsetHeight;
        if (
            event.clientX < left ||
            event.clientX > right ||
            event.clientY < top ||
            event.clientY > bottom
        ) {
            onMouseUp();
        }
    }
    function onMouseUp() {
        document.removeEventListener("mousemove", onMouseMove);
        document.removeEventListener("mouseup", onMouseUp);
        document.ondragstart = null;
        document.ondragend = null;
        boxWrapperRef.value.classList.remove("axis-wrapper--dragged");
        status.value = operateType.DEFAULT;
    }
}
